<!-- Bot Read Me -->
<!-- Author: Edwin -->
<template>
  <el-dialog
    style="width: 100%; height: 100%"
    :withHeader="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="951px"
    :visible.sync="visible"
    @close="canceldialog"
  >
    <div v-if="visible" class="bot-read-me">
      <div class="bot-read-me-content">
        <el-form
          :model="dataForm"
          :rules="dataRules"
          ref="dataForm"
          :inline="false"
          v-loading="loading"
          @keyup.enter.native="dataFormSubmitHandle()"
          label-width="120px"
        >
          <div style="height: 600px; overflowy: auto; padding: 20px">
            <el-form-item label="API Name" prop="name">
              <el-input v-model="dataForm.name"></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.method')" prop="method">
              <el-select v-model="dataForm.method" style="width: 100%">
                <el-option
                  v-for="item in methodSelect"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.path')" prop="path">
              <el-input v-model="dataForm.path"></el-input>
            </el-form-item>
            <el-form-item label="Sync Client" prop="syncClient">
              <el-input v-model="dataForm.syncClient"></el-input>
            </el-form-item>
            <el-form-item label="Sync Path" prop="syncPath">
              <el-input v-model="dataForm.syncPath"></el-input>
            </el-form-item>
            <el-form-item label="Sync Open" prop="syncOpen">
              <el-checkbox v-model="dataForm.syncOpen"></el-checkbox>
            </el-form-item>
            <el-form-item label="Delete Open" prop="deleteOpen">
              <el-checkbox v-model="dataForm.deleteOpen"></el-checkbox>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.sourceMapping')"
              prop="sourceMapping"
            >
              <el-input v-model="dataForm.sourceMapping"></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.prodMapping')"
              prop="prodMapping"
            >
              <el-input v-model="dataForm.prodMapping"></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.subjectCode')"
              prop="subjectCode"
            >
              <el-select
                v-model="dataForm.subjectCode"
                :placeholder="$t('custom.dataset.integration')"
                style="width: 90%"
              >
                <el-option
                  v-for="its in integrationList"
                  :key="its.subjectCode"
                  :label="its.name"
                  :value="its.subjectCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="roles" :label="$t('custom.dataset.role')">
              <el-select
                v-model="dataForm.roles"
                filterable
                clearable
                multiple
                collapse-tags
                default-first-option
                :placeholder="$t('custom.dataset.role')"
                style="width: 90%"
              >
                <el-option
                  v-for="its in fullRoleList"
                  :key="its.id"
                  :label="its.name"
                  :value="its.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.apiDoc')" prop="apiDoc">
              <el-input v-model="dataForm.apiDoc"></el-input>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.syncRate')"
              prop="syncRate"
            >
              <el-select
                v-model="dataForm.syncRate"
                filterable
                :placeholder="$t('custom.botStore.syncRate')"
                style="width: 100%"
              >
                <el-option
                  v-for="its in syncRateList"
                  :key="its.dictValue"
                  :label="its.dictLabel"
                  :value="its.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.isShow')" prop="isShow">
              <el-checkbox v-model="dataForm.isShow"></el-checkbox>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.apiService')"
              prop="apiService"
            >
              <el-input v-model="dataForm.apiService"></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.apiPath')" prop="apiPath">
              <el-input v-model="dataForm.apiPath"></el-input>
            </el-form-item>

            <el-form-item
              :label="$t('custom.botStore.prodMappingType')"
              prop="prodMappingType"
            >
              <el-select
                v-model="dataForm.prodMappingType"
                style="width: 100%"
                placeholder="Please Select Mapping Type"
              >
                <el-option
                  v-for="item in mappingList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.action')" prop="action">
              <el-input v-model="dataForm.action"></el-input>
            </el-form-item>
            <el-form-item label="Delete Action" prop="deleteAction">
              <el-input v-model="dataForm.deleteAction"></el-input>
            </el-form-item>

            <el-form-item :label="$t('custom.botStore.pid')" prop="pid">
              <el-select
                v-model="dataForm.pid"
                style="width: 100%"
                @change="pidChange"
                filterable
              >
                <el-option
                  v-for="item in pidOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="client" prop="client">
              <el-input
                v-model="dataForm.client"
                :disabled="dataForm.pid.length != ''"
              ></el-input>
            </el-form-item>
            <el-form-item :label="$t('custom.botStore.params')" prop="params">
              <v-jsoneditor
                v-model="dataForm.params"
                :options="jsoneditorSetting.options"
                :plus="jsoneditorSetting.plus"
                :height="jsoneditorSetting.height"
                :indentation="jsoneditorSetting.indentation"
                :search="jsoneditorSetting.search"
                :path="jsoneditorSetting.path"
                :color="jsoneditorSetting.color"
                @error="onError"
              ></v-jsoneditor>
            </el-form-item>
            <el-form-item
              :label="$t('custom.botStore.paramsDataset')"
              prop="paramsDataset"
            >
              <v-jsoneditor
                v-model="dataForm.paramsDataset"
                :options="jsoneditorSetting.options"
                :plus="jsoneditorSetting.plus"
                :height="jsoneditorSetting.height"
                :indentation="jsoneditorSetting.indentation"
                :search="jsoneditorSetting.search"
                :path="jsoneditorSetting.path"
                :color="jsoneditorSetting.color"
                @error="onError"
              ></v-jsoneditor>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    <template slot="footer">
      <el-button size="small" @click="canceldialog">{{
        $t('cancel')
      }}</el-button>
      <el-button
        size="small"
        type="primary"
        @click="dataFormSubmitHandle(false)"
        >{{ $t('custom.botStore.save') }}</el-button
      >
      <el-button
        size="small"
        type="primary"
        v-show="isShowGenerate"
        @click="validateDatasetName()"
        >Generate Dataset</el-button
      >
    </template>
  </el-dialog>
</template>
<script>
import qs from 'qs'
import { getUUID } from '@/utils'

export default {
  components: {},
  data() {
    return {
      loading: false,
      visible: false,
      dataForm: {
        name: '',
        client: '',
        syncOpen:false,
        deleteOpen:false,
        method: '',
        path: '',
        syncClient:'',
        syncPath:'',
        params: {},
        pid: [],
        paramsDataset: {},
        sourceMapping: '',
        prodMapping: '',
        prodMappingType: null,
        action: '',
        deleteAction:'',  
        apiDoc: null,
        syncRate: null,
        subjectCode: null,
        isShow: 0,
        apiService: null,
        apiPath: null,
        roles: []
      },
      mappingList: [
        {
          value: 0,
          label: 'Table'
        },
        {
          value: 1,
          label: 'Materialized View'
        }
      ],
      pidOptions: [],
      jsoneditorSetting: {
        options: { mode: 'tree', modes: ['tree', 'code'] },
        plus: false,
        height: '400px',
        indentation: 2,
        search: true,
        color: 'red',
        path: false
      },
      methodSelect: [
        {
          label: 'GET',
          value: 'GET'
        },
        {
          label: 'POST',
          value: 'POST'
        },
        {
          label: 'PUT',
          value: 'PUT'
        },
        {
          label: 'DELETE',
          value: 'DELETE'
        }
      ],
      integrationList: [],
      equalObj: {
        name: '',
        client: '',
        method: '',
        path: '',
        params: {},
        pid: [],
        paramsDataset: {},
        sourceMapping: '',
        prodMapping: '',
        prodMappingType: null,
        action: '',
        deleteAction:'',
        apiDoc: null,
        syncRate: null,
        subjectCode: null,
        isShow: 0,
        apiService: null,
        apiPath: null,
        roles: []
      },
      roleList: [],
      assignRoleList: []
    }
  },
  computed: {
    dataRules() {
      return {
        name: [
          {
            required: true,
            message: this.$t('custom.botStore.nameRules'),
            trigger: 'blur'
          }
        ],
        roles: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
        // client: [
        //   { required: true, message: this.$t('custom.botStore.clientRules'), trigger: 'blur' }
        // ]
      }
    },
    syncRateList() {
      let temp = []
      let list = window.SITE_CONFIG['dictList'].find(
        e => e.dictType === 'api_sync_rate'
      ).dataList
      for (let index = 0; index < list.length; index++) {
        const element = list[index].dictValue
        temp.push({
          dictValue: Number(element),
          dictLabel: list[index].dictLabel
        })
      }
      return temp
    },
    isShowGenerate() {
      let temp = false
      if (
        this.dataForm.id &&
        this.dataForm.roles &&
        this.dataForm.roles.length > 0
      ) {
        if (this.check()) {
          temp = true
        }
      }
      return temp
    },
    fullRoleList() {
      let roleList = this.roleList
      let assignRoleList = this.assignRoleList
      let roleTemp = []
      let assignTemp = []
      let temp = []
      roleList.forEach(ii => {
        roleTemp.push({
          roleId: ii.roleId,
          name: ii.name
        })
      })
      assignRoleList.forEach(it => {
        assignTemp.push({
          roleId: it.assignId,
          name: ''
        })
      })
      temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
      return temp
    }
  },
  methods: {
    check() {
      return this._.isEqual(this.dataForm, this.equalObj)
    },
    pidChange(value) {
      for (let i = 0; i < this.pidOptions.length; i++) {
        var object = this.pidOptions[i]
        if (value === object.value) {
          this.$set(this.dataForm, 'client', object.client)
        }
      }
      this.$refs['dataForm'].clearValidate('client')
    },
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        } else {
          this.dataForm.roles = ['1125415693534105602', '1266700345287905282']
        }
        this.initOptions()
        this.getIntegrationList()
        this.getRoleList()
        this.getAssignRoleList()
      })
    },
    onError(value) {},
    getRoleList() {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.system
        .getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
          if (this.dataForm.id) {
            this.getInfo()
          } else {
            this.loading = false
          }
        })
        .catch(() => {})
    },
    getAssignRoleList() {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      var params = qs.stringify(
        {
          roleId: temp
        },
        { arrayFormat: 'repeat' }
      )
      this.$interface.um.getAssignRoleList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.assignRoleList = res.data
      })
    },
    getInfo() {
      this.loading = true
      const params = {
        id: this.dataForm.id
      }
      this.$interface.apiManager
        .queryApiManegreInfoApi(params)
        .then(({ data: res }) => {
          if (!res) {
            return this.$message.error(res.msg)
          }
          if (!res.data.roles) {
            res.data.roles = ['1125415693534105602', '1266700345287905282']
          }
          if (res.data.isShow === 1) {
            res.data.isShow = true
          } else {
            res.data.isShow = false
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          this.equalObj = {
            ...this.equalObj,
            ...res.data
          }
          this.loading = false
        })
        .catch(() => {})
    },
    verifyForm() {
      return this.$refs['dataForm'].validate()
    },
    dataFormSubmitHandle(isVisible) {
      this.verifyForm().then(() => {
        this.dataForm.language = 'Groovy'
        if (this.dataForm.isShow) {
          this.dataForm.isShow = 1
        } else {
          this.dataForm.isShow = 0
        }
        const params = {
          ...this.dataForm
        }
        const changeScriptInfo = () => {
          if (!this.dataForm.id) {
            return this.$interface.apiManager.saveApiManegreApi(params)
          } else {
            return this.$interface.apiManager.updateApiManegreApi(params)
          }
        }
        changeScriptInfo()
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.$emit('refreshDataList')
            this.visible = isVisible
            this.$message.success(res.msg)
          })
          .catch(() => {})
      })
    },
    canceldialog() {
      this.visible = false
      this.equalObj = {
        name: '',
        client: '',
        method: '',
        path: '',
        params: {},
        pid: [],
        paramsDataset: {},
        sourceMapping: '',
        prodMapping: '',
        prodMappingType: null,
        action: '',
        deleteAction:'',  
        apiDoc: null,
        syncRate: null,
        subjectCode: null,
        isShow: 0,
        apiService: null,
        apiPath: null,
        roles: []
      }
      this.dataForm = {
        name: '',
        client: '',
        method: '',
        path: '',
        params: {},
        pid: [],
        paramsDataset: {},
        sourceMapping: '',
        prodMapping: '',
        prodMappingType: null,
        action: '',
        deleteAction:'',
        apiDoc: null,
        syncRate: null,
        subjectCode: null,
        isShow: 0,
        apiService: null,
        apiPath: null,
        roles: []
      }
    },
    async initOptions() {
      this.pidOptions = [{ id: '', value: '', client: '' }]
      const { data: res } =
        await this.$interface.apiManager.queryApiManegreListApi()
      for (let i = 0; i < res.data.length; i++) {
        this.pidOptions.push({
          label: res.data[i].name,
          value: res.data[i].id,
          client: res.data[i].client
        })
      }
    },
    createDataset() {
      const params = {
        name: this.dataForm.name,
        integration: [this.dataForm.subjectCode],
        businessId: getUUID(),
        language: 'sql',
        formCode: null,
        type: 1,
        content:
          'select * from ' +
          this.dataForm.prodMapping +
          ' where tenant_code={tenant_code}',
        dataWarehouseLayer: 'ods',
        apiList: [this.dataForm.id],
        tenantCode: '1001', // this.$store.state.user.tenantCode, // '1001'
        status: 'Published',
        refreshType: 'javaapi',
        description: `ODS Dataset which generated from ${this.dataForm.name}`,
        roleIdList: this.dataForm.roles, // ['1125415693534105602', '1266700345287905282'],
        internalNotes: `${this.dataForm.name} / ${this.dataForm.id}`,
        businessType: 'Template', // Template
        rentention: null,
        refreshContent: null,
        botAfterRefresh: true,
        refreshCron: null,
        botCron: null,
        createContent: null,
        owner: null,
        cronContent: null,
        refreshName: null
      }
      this.$interface.reports
        .postReportDatasetApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
        })
    },
    validateDatasetName() {
      if (!this.dataForm.roles) {
        return
      }
      if (!this.dataForm.id) {
        return
      }
      if (!this.dataForm.name) {
        return this.$message.error(this.$t('custom.botStore.nameRules'))
      }
      let params = {
        name: this.dataForm.name.trim(),
        isNew: true,
        businessType: 'Custom',
        tenantCode: this.$store.state.user.tenantCode, // '1001'
        datasetId: ''
      }
      this.$interface.reports.postCheckNameApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error('The name is already exists')
        }
        this.createDataset()
      })
    },
    getIntegrationList() {
      this.integrationList = []
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager
        .getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            tempList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status
            })
          }
          this.integrationList = tempList
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
@import 'src/views/modules/mspbots/bots/my-bots/my-bot';
.bot-read-me{
  overflow: auto;
}
</style>
